using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;

using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Diagnostics;
using System.Text;
using Microsoft.Office.Server.UserProfiles;
using System.Web.UI.WebControls;

namespace CSP.WebParts
{
    [Guid("68c06400-3791-420b-a2cc-e8103c0e0f41")]
    public class CSPFollowMe : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private bool _error = false;
        private string _myProperty = null;

        enum followState { NONE, FOLLOWME, FOLLOWING, WAITINGAPPROVAL };

        ImageButton btnFollowMe = null;
        followState _followState = followState.NONE;


        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("My Property Group")]
        [WebDisplayName("MyProperty")]
        [WebDescription("Meaningless Property")]
        public string MyProperty
        {
            get
            {
                if (_myProperty == null)
                {
                    _myProperty = "Hello SharePoint";
                }
                return _myProperty;
            }
            set { _myProperty = value; }
        }


        public CSPFollowMe()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()
        {
            if (!_error)
            {
                try
                {
                    //RMV:
                    //Controls.Clear();
                    //                   

                    base.CreateChildControls();

                    //RMV: Initialized follow me control
                    InitFollowButtonControls();


                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        //
        private void InitFollowButtonControls()
        {
            //Create button
            InitFollowButtonState();
            UpdateFollowUpState();
        }

        //RMV 8/20/2009
        // InitFollowButtonState(): Initialized the state of the follow button to be presented in the page
        //POST CONDITION
        // _followState = followState.FOLLOWING: If user is already in account and approved.
        // _followState = followState.WAITINGAPPROVAL: If user is already in account and waiting for approval
        // _followState = followState.FOLLOWME: User is not yet a follower
        private void InitFollowButtonState()
        {
            const string FOLLOWER_REQUEST_LIST = "Follower requests";
            string userAcc = string.Empty;  //Passed from the borwser
            string currentLoggedUser = string.Empty;

            SPSite siteColl = null;
            SPWeb site = null;

            siteColl = SPContext.Current.Site;
            site = SPContext.Current.Web;

            _followState = followState.NONE;

            try
            {
                //The account can only be obtained from the browser
                string accountname = this.Context.Request.QueryString["accountname"];
                if (accountname == null)
                    return;
                string[] splittedAccountName = null;

                if (accountname != null)
                    splittedAccountName = accountname.Split('\\');
                //Split the acount CONTOSO\user
                if (splittedAccountName != null && splittedAccountName.Length > 1)
                    userAcc = splittedAccountName[1];

            

                SPUser currentuser = site.CurrentUser;
                if (currentuser != null)
                    currentLoggedUser = currentuser.LoginName;

   

                //if a useraccount is not in browser then do nothing
                if (userAcc.Length == 0)
                    return;

                //Make sure accountname is not the same surrent user
                if (accountname == currentuser.LoginName)
                    return;

                //List to search
                string urlString = site.Url;
                Debug.WriteLine("URL String = {0}", urlString);

                string listname = "/personal/" + userAcc;
                string pageurl = urlString + listname;

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite ElevatedsiteColl = new SPSite(pageurl))
                    {
                        using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb())
                        {
                            if (ElevatedSite == null || ElevatedSite.Lists == null)
                                return;

                            if (listExists(ElevatedSite.Lists, FOLLOWER_REQUEST_LIST) == false)
                            {
                                //Note: This should not happen once the feauture is activated in all site
                                _followState = followState.NONE;
                                UpdateFollowUpState();
                                return;

                            }

                            string currentLoginName = SPContext.Current.Web.CurrentUser.LoginName;
                       
                            SPUser currUser = SPContext.Current.Web.CurrentUser;

                            List<Colleague> colls = new List<Colleague>();
                            colls = CSP.Model.DataAccess.SPDataAccess.getColleagues(currentLoginName);

                            foreach (Colleague c in colls)
                            {
                                if (c.Profile["AccountName"].Value.ToString() == accountname)
                                {
                                    _followState = followState.FOLLOWING;
                                    return;
                                }
                            }

                            SPList idList = ElevatedSite.Lists[FOLLOWER_REQUEST_LIST];
                            if (idList != null)
                            {
                                foreach (SPListItem item in idList.Items)
                                {
                                    SPFieldUser follower = (SPFieldUser)item.Fields["Follower"];
                                    SPFieldUserValue user = (SPFieldUserValue)follower.GetFieldValue(item["Follower"].ToString());
                                    SPUser currentFollower = user.User;

                                    //Make sure the user does not already exist in the list                                   
                                    //string currentFollower = item["Follower"].ToString().ToLower();
                                    string strCurrentFollower = currentFollower.LoginName;
                                    if (strCurrentFollower.ToLower().Contains(currentLoggedUser.ToLower()))
                                    {
                                        Boolean approved = Convert.ToBoolean(item["IsAllowed"]);
                                        if (approved != true)
                                            //_followState = followState.FOLLOWING;
                                            //else
                                            _followState = followState.WAITINGAPPROVAL;

                                        return;

                                    }

                                    strCurrentFollower = item["Follower"].ToString().ToLower();
                                    //User was found
                                    if (strCurrentFollower.Contains(currentLoggedUser.ToLower()))
                                    {
                                        Boolean approved = Convert.ToBoolean(item["IsAllowed"]);
                                        if (approved != true)
                                            //_followState = followState.FOLLOWING;
                                            //else
                                            _followState = followState.WAITINGAPPROVAL;

                                        return;

                                    }
                                }
                            }
                        }
                    }
                });

                string currentUserACc = string.Empty;

                if (currentuser != null)
                    currentLoggedUser = currentuser.LoginName;
                currentLoggedUser = currentLoggedUser.Replace("dhalstead", "deanh");
                splittedAccountName = null;
                if (currentLoggedUser != null)
                    splittedAccountName = currentLoggedUser.Split('\\');
                //Split the acount CONTOSO\user
                if (splittedAccountName != null && splittedAccountName.Length > 1)
                    currentUserACc = splittedAccountName[1];

                pageurl = pageurl.Replace(userAcc, currentUserACc);
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite ElevatedsiteColl = new SPSite(pageurl))
                    {
                        using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb())
                        {
                            if (ElevatedSite == null || ElevatedSite.Lists == null)
                                return;



                            if (listExists(ElevatedSite.Lists, FOLLOWER_REQUEST_LIST) == false)
                            {
                                //Note: This should not happen once the feauture is activated in all site
                                _followState = followState.NONE;
                                UpdateFollowUpState();
                                return;
                            }

                            string currentLoginName = SPContext.Current.Web.CurrentUser.LoginName;
                            currentLoginName = currentLoginName.Replace("dhalstead", "deanh");
                            SPUser currUser = SPContext.Current.Web.CurrentUser;

                            //List<Colleague> colls = new List<Colleague>();
                            //colls = CSP.Model.DataAccess.SPDataAccess.getColleagues(currentLoginName);

                            //foreach (Colleague c in colls)
                            //{
                            //    if (c.Profile["AccountName"].Value.ToString() == accountname)
                            //    {
                            //        _followState = followState.FOLLOWING;
                            //        return;
                            //    }
                            //}

                            SPList idList = ElevatedSite.Lists[FOLLOWER_REQUEST_LIST];
                            if (idList != null)
                            {
                                foreach (SPListItem item in idList.Items)
                                {
                                    SPFieldUser follower = (SPFieldUser)item.Fields["Follower"];
                                    SPFieldUserValue user = (SPFieldUserValue)follower.GetFieldValue(item["Follower"].ToString());
                                    SPUser currentFollower = user.User;

                                    //Make sure the user does not already exist in the list                                   
                                    //string currentFollower = item["Follower"].ToString().ToLower();
                                    string strCurrentFollower = currentFollower.LoginName;
                                    if (strCurrentFollower.ToLower().Contains(accountname.ToLower()))
                                    {
                                        Boolean approved = Convert.ToBoolean(item["IsAllowed"]);
                                        if (approved == true)
                                        {    //_followState = followState.FOLLOWING;
                                            //else
                                            _followState = followState.FOLLOWING;
                                            UpdateFollowUpState();
                                            return;
                                        }

                                    }

                                    strCurrentFollower = item["Follower"].ToString().ToLower();
                                    //User was found
                                    if (strCurrentFollower.Contains(accountname.ToLower()))
                                    {
                                        Boolean approved = Convert.ToBoolean(item["IsAllowed"]);
                                        if (approved == true)
                                        {  //_followState = followState.FOLLOWING;
                                            //else
                                            _followState = followState.FOLLOWING;
                                            UpdateFollowUpState();
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //User to be added is not yet a follower
                    _followState = followState.FOLLOWME;
                });

            }
            catch (Exception exp)
            {

                Debug.WriteLine(exp.ToString());
                HandleException(exp);

            }
        }

        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            if (!_error)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();
                    //RMV: Uncomment script control . DO NOT DELETE IT for future reference
                    //       this.Page.ClientScript.RegisterClientScriptInclude("FollowMe", "~/_layouts/CSP%20Follow%20Me/FollowMe.js");


                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }

        //RV Dont't DELETE.  For refrence
        protected override void RenderContents(HtmlTextWriter writer)
        {
            base.RenderContents(writer);


            ////    writer.Write("<input type=\"button\" id=\"btnHidden\" style=\"display:none\" runat=\"server\" onserverclick=\"click_test\">");
            ////    writer.Write("<span id=\"link0\" onmouseover=\"displayFollowRequest (0);\" onmouseout=\"hideFollowRequest();\"><img src=\"followme.gif\" alt=\"Follow Me!\" /></span>");
            ////    writer.Write("<div id=\"tooltipBox\" onmouseover=\"clearRequestInterval();highlightRequest('itxtTbl');\" onmouseout=\"hideFollowRequest();unhighlightRequest('itxtTbl');\" style=\"z-index:5000;position:absolute;cursor:pointer;\"></div>");
        }

        //Renders the HTML for the body of a Web Part to the client
        //protected override void RenderWebPart(HtmlTextWriter output)
        //{
        //    RenderChildren(output);
        //}


        //protected void btnSubmitFollowMe_ClientClick(object sender, EventArgs e)
        public void btnFollowMe_Click(object sender, ImageClickEventArgs e)
        {
            writeToFollowerList();
        }

        protected void writeToFollowerList()
        {
            const string FOLLOWER_REQUEST_LIST = "Follower requests";
            string userAcc = string.Empty;  //Passed from the borwser
            string currentLoggedUser = string.Empty;

            SPSite siteColl = null;
            SPWeb site = null;

            siteColl = SPContext.Current.Site;
            site = SPContext.Current.Web;

            try
            {
                //The account can only be obtained from the browser
                string accountname = this.Context.Request.QueryString["accountname"];

                if (accountname == null)
                    return;

                string[] splittedAccountName = null;

                if (accountname != null)
                    splittedAccountName = accountname.Split('\\');

                //Split the acount CONTOSO\user
                if (splittedAccountName != null && splittedAccountName.Length > 1)
                    userAcc = splittedAccountName[1];

                SPUser currentuser = SPContext.Current.Web.CurrentUser;
                if (currentuser != null)
                    currentLoggedUser = currentuser.LoginName;

                currentLoggedUser = currentLoggedUser.Replace("dhalstead", "deanh");

                //if a useraccount is not in browser then do nothing
                if (userAcc.Length == 0)
                    return;

                //Make sure accountname is not the same surrent user
                if (accountname == currentuser.LoginName)
                    return;

                //List to search
                string urlString = site.Url;
                Debug.WriteLine("URL String = {0}", urlString);

                string listname = "/personal/" + userAcc;
                string pageurl = urlString + listname;

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite ElevatedsiteColl = new SPSite(pageurl))
                    {
                        using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb())
                        {
                            if (ElevatedSite == null || ElevatedSite.Lists == null)
                                return;

                            //IMPORTANT: Allow update to the database.
                            ElevatedSite.AllowUnsafeUpdates = true;

                            if (listExists(ElevatedSite.Lists, FOLLOWER_REQUEST_LIST) == false)
                            {
                                //Note: This should not happen once the feauture is activated in all site
                                _followState = followState.NONE;
                                UpdateFollowUpState();
                                return;

                            }

                            SPList idList = ElevatedSite.Lists[FOLLOWER_REQUEST_LIST];


                            if (idList != null)
                            {
                                foreach (SPListItem item in idList.Items)
                                {
                                    //Make sure the user does not already exist in the list
                                    // string currentFollower = item["Follower"].ToString().Replace("5;#", "");
                                    string currentFollower = item["Follower"].ToString().ToLower();

                                    SPFieldUser follower = (SPFieldUser)idList.Fields["Follower"];
                                    SPFieldUserValue user = (SPFieldUserValue)follower.GetFieldValue(item["Follower"].ToString());
                                    SPUser userObject = user.User;
                                    string l = userObject.LoginName;

                                    //User was found
                                    if (currentFollower.Contains(currentLoggedUser.ToLower()))
                                        return;

                                }

                                SPListItem listItemAdd = idList.Items.Add();
                                SPUser spuser = ElevatedSite.AllUsers[currentLoggedUser];
                                listItemAdd["Follower"] = spuser;
                                listItemAdd.Update();

                                //Change the followstate
                                _followState = followState.WAITINGAPPROVAL;
                                UpdateFollowUpState();
                            }
                        }
                    }
                });

            }
            catch (Exception exp)
            {

                Debug.WriteLine(exp.ToString());
                HandleException(exp);

            }

        }

        private void UpdateFollowUpState()
        {
            if (btnFollowMe != null)
            {
                btnFollowMe.Visible = false;
            }

            switch (_followState)
            {
                case followState.FOLLOWING:
                    btnFollowMe = new ImageButton();
                    btnFollowMe.ImageUrl = "~/_layouts/CSP Follow Me/following.gif";
                    btnFollowMe.Enabled = false;
                    break;
                case followState.FOLLOWME:
                    btnFollowMe = new ImageButton();
                    btnFollowMe.ImageUrl = "~/_layouts/CSP Follow Me/followme.gif";
                    btnFollowMe.Enabled = true;
                    btnFollowMe.Click += new ImageClickEventHandler(btnFollowMe_Click);
                    break;
                case followState.WAITINGAPPROVAL:
                    btnFollowMe = new ImageButton();
                    btnFollowMe.ImageUrl = "~/_layouts/CSP Follow Me/approval.gif";
                    btnFollowMe.Enabled = false;
                    break;
                default:
                    break;
            }
            if (btnFollowMe != null)
            {
                btnFollowMe.Visible = true;
                Controls.Add(btnFollowMe);

            }

        }

        bool listExists(SPListCollection collection, string title)
        {
            foreach (SPList list in collection)
            {
                if (list.Title == title)
                {
                    return true;
                }
            }
            return false;
        }


        //Need LINQ reference
        //public static bool ListExists(SPWeb web, string listName)
        //{
        //    return web.Lists.Cast<SPList>().Any(list => string.Equals(list.Title, listName));
        //}


        //void click_test(object sender, EventArgs a)
        //{
        //    Debug.WriteLine("click_test");
        //}

        //    string GetUserName()
        //    {
        //        string str = string.Empty;
        //        if (Context.User.Identity.IsAuthenticated)
        //        {
        //            SPContext context = SPContext.Current;

        //            try
        //            {
        //                SPWeb web = SPContext.Current.Web;
        //                {
        //                    SPList idList = web.Lists["Tweets"];
        //                    foreach (SPListItem item in idList.Items)
        //                    {
        //                        if (item["Title"].ToString() == "Test")
        //                        {
        //                            str = item["Title"].ToString();
        //                            break;
        //                        }
        //                    }
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                Debug.WriteLine(ex.ToString());
        //                str = Context.User.Identity.Name;
        //            }
        //        }
        //        else
        //        {
        //            str = Context.User.Identity.Name;
        //        }
        //        return str;
        //    }

    }
}
